import unittest
import os
import logging
from generic_logger import get_logger, LoggerManager, setup_logger
from generic_logger.handlers import CustomRotatingFileHandler, CustomTimedRotatingFileHandler

class LoggerTestCase(unittest.TestCase):
    def setUp(self):
        # 清理测试日志文件
        if os.path.exists('logs/test.log'):
            os.remove('logs/test.log')
        if os.path.exists('logs/test_rotating.log'):
            os.remove('logs/test_rotating.log')
        if os.path.exists('logs/test_timed.log'):
            os.remove('logs/test_timed.log')

    def test_get_logger(self):
        logger = get_logger('test')
        logger.info('Test message')
        self.assertTrue(os.path.exists('logs/test.log'))

    def test_logger_manager(self):
        manager = LoggerManager()
        logger1 = manager.get_logger('test_manager')
        logger1.info('Test message from manager')
        self.assertTrue(os.path.exists('logs/test_manager.log'))

    def test_preset_config(self):
        manager = LoggerManager()
        logger = manager.get_logger('test_preset', preset='prod')
        logger.info('Test message with prod preset')
        self.assertTrue(os.path.exists('logs/test_preset.log'))

    def test_rotating_handler(self):
        logger = setup_logger(
            log_file='logs/test_rotating.log',
            handler_type='size',
            max_bytes=1024,  # 1KB
            backup_count=3
        )
        for i in range(10):
            logger.info(f'Test message {i}')
        self.assertTrue(os.path.exists('logs/test_rotating.log'))

    def test_timed_handler(self):
        logger = setup_logger(
            log_file='logs/test_timed.log',
            handler_type='time',
            when='S',  # 每秒轮转
            backup_when=3
        )
        logger.info('Test message for timed handler')
        self.assertTrue(os.path.exists('logs/test_timed.log'))

    def test_custom_handlers(self):
        rotating_handler = CustomRotatingFileHandler(
            'logs/test_custom_rotating.log',
            maxBytes=1024,
            backupCount=3
        )
        timed_handler = CustomTimedRotatingFileHandler(
            'logs/test_custom_timed.log',
            when='S',
            backupCount=3
        )
        self.assertIsInstance(rotating_handler, logging.Handler)
        self.assertIsInstance(timed_handler, logging.Handler)

    def test_file_only_preset(self):
        manager = LoggerManager()
        logger = manager.get_logger('test_file_only', preset='file_only')
        logger.info('Test message with file_only preset')
        self.assertTrue(os.path.exists('logs/test_file_only.log'))
        # Verify no console output
        self.assertEqual(logger.handlers[0].stream, None)

    def test_preset_with_config(self):
        manager = LoggerManager()
        # 使用预设配置并覆盖部分参数
        logger = manager.get_logger(
            'test_combined',
            preset='prod',
            config={'max_bytes': 2048}  # 覆盖预设的max_bytes值
        )
        logger.info('Test message with combined config')
        self.assertTrue(os.path.exists('logs/test_combined.log'))

    def test_use_preset(self):
        """测试use_preset方法的功能"""
        # 创建测试目录
        test_dir = 'preset_logs'
        if os.path.exists(test_dir):
            import shutil
            shutil.rmtree(test_dir)

        # 测试1: 使用use_preset设置默认配置
        manager = LoggerManager(base_dir=test_dir)
        manager.use_preset('dev')  # 设置为开发环境配置

        # 验证默认配置已更新
        self.assertEqual(manager._default_config['level'], logging.DEBUG)
        self.assertTrue(manager._default_config['console'])
        self.assertTrue(manager._default_config['show_file_line'])

        # 测试2: 不指定配置时应使用默认配置
        logger = manager.get_logger('test_use_preset')
        logger.debug('Test debug message with dev preset')  # 使用DEBUG级别
        self.assertTrue(os.path.exists(f'{test_dir}/test_use_preset.log'))

        # 测试3: 验证链式调用
        chain_logger = manager.use_preset('prod').get_logger('test_chain')
        self.assertEqual(chain_logger.level, logging.INFO)  # prod配置使用INFO级别
        chain_logger.info('Test chain call')
        self.assertTrue(os.path.exists(f'{test_dir}/test_chain.log'))

        # 清理测试目录
        if os.path.exists(test_dir):
            import shutil
            shutil.rmtree(test_dir)

    def test_custom_base_dir(self):
        # 测试目录
        test_dir = 'custom_logs'

        # 确保测试目录不存在
        if os.path.exists(test_dir):
            import shutil
            shutil.rmtree(test_dir)

        # 测试1: 使用get_logger函数指定base_dir
        logger1 = get_logger('test_custom_dir', base_dir=test_dir)
        logger1.info('Test message with custom base_dir')
        self.assertTrue(os.path.exists(f'{test_dir}/test_custom_dir.log'))

        # 测试2: 使用LoggerManager类指定base_dir
        manager = LoggerManager(base_dir='manager_logs')
        logger2 = manager.get_logger('test_manager_dir')
        logger2.info('Test message with manager base_dir')
        self.assertTrue(os.path.exists('manager_logs/test_manager_dir.log'))

        # 测试3: 使用setup_logger函数指定base_dir
        logger3 = setup_logger(
            module_name='test_setup_dir',
            base_dir='setup_logs'
        )
        logger3.info('Test message with setup_logger base_dir')
        self.assertTrue(os.path.exists('setup_logs/test_setup_dir.log'))

        # 清理测试目录
        if os.path.exists(test_dir):
            import shutil
            shutil.rmtree(test_dir)
        if os.path.exists('manager_logs'):
            shutil.rmtree('manager_logs')
        if os.path.exists('setup_logs'):
            shutil.rmtree('setup_logs')

if __name__ == '__main__':
    unittest.main()